package com.ge.med.cchelper.popup.job;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import com.ge.med.cchelper.bean.Response;
import com.ge.med.cchelper.util.LogUtil;
import com.ge.med.cchelper.util.ReourceHelper;
import com.ge.med.cchelper.util.SSLhelper;
import com.ge.med.cchelper.util.TextHelper;
import com.ge.med.cchelper.util.ftp.FTPFactory;
import com.ge.med.cchelper.util.ftp.FtpHelper;

public class UnCheckoutJob extends BaseJob{

	private IFile selectedIFile;

	
	public UnCheckoutJob(String message,IFile selectedIFile) {
		super(message);
		this.selectedIFile = selectedIFile;	
	}

	
	protected IStatus start(IProgressMonitor arg0) {
		String noUse = selectedIFile.getFullPath().segment(1);
		String allPath = selectedIFile.getFullPath().toString();
		String realTempPath = allPath.substring(allPath
				.indexOf(noUse) + noUse.length());
		String fileName = selectedIFile.getFullPath()
				.lastSegment();

		String fullPath = selectedIFile.getLocation()
				.toOSString();
		String vobsPath = csession.getVobRoot();
		String remotePath = vobsPath + realTempPath;

		LogUtil.out("uncheckout " + fileName + "...");

		SSLhelper sslHelper = new SSLhelper(csession);

		// uncheckout source
		Response res0 = sslHelper.executeUNCheckout(remotePath);
		int flag0 = res0.getStatus();
		if (flag0 == 0) {
			Response res = sslHelper.executeCT("cp -rf "
					+ remotePath + " " + sourceTempDir);
			int flag = res.getStatus();
			if (flag == 0) {
				FtpHelper ftp = null;

				try {
					ftp = FTPFactory.getConnectionInstance(csession.getHost(), ".");
					if (ftp.downloadPlus(sourceTempDir + "/"
							+ fileName, fullPath,arg0,false)) {
						sslHelper.execute("rm -rf "
								+ sourceTempDir + "/"
								+ fileName);
					}
				} catch (Exception e) {
					LogUtil.err(e.getMessage());
					e.printStackTrace();
					return Status.CANCEL_STATUS;
				}
			} else {
				return Status.CANCEL_STATUS;
			}

		}else{
			return Status.CANCEL_STATUS;
		}

		LogUtil.out("unCheckout completed.");
		
		try {
			IProject currentProject =ReourceHelper.getProject();
			String confdir =  currentProject.getLocation().toOSString();
			TextHelper.remove(confdir+File.separator+TextHelper.CHECKOUT_FILE, allPath);
		} catch (Exception e1) {
			e1.printStackTrace();
			LogUtil.err("remove checkout flag failed."
					+ e1.getMessage());
		}
		
		try {
			selectedIFile.refreshLocal(IResource.DEPTH_ONE, null);
		} catch (CoreException e) {
			e.printStackTrace();
			LogUtil.err("refresh failed."
					+ e.getMessage());
		}
		return Status.OK_STATUS;
	}

}
